package com.example.qqemailtest.listener;

import com.example.qqemailtest.bean.User;
import com.example.qqemailtest.tool.RandomCode;
import com.example.qqemailtest.tool.SendSimpleMailTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RegistryListener implements ApplicationListener<RegisteryListenerEvent> {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SendSimpleMailTool sendSimpleMailTool;
    @Autowired
    RandomCode randomCode;

    @Override
    public void onApplicationEvent(RegisteryListenerEvent event) {
        System.out.println("监听到用户在注册 " + event.toString());
        String  Vcode;
        while (true){
            //        生成验证码
          Vcode = randomCode.creatCode();
            log.info("验证码========"+Vcode);
//    判断redis中是否有这个验证码,如果有重写生成
           Object o = redisTemplate.opsForValue().get(Vcode);
            if (o==null){  //为null说明没有这个值,可以使用   //最好存储在session中,这里使用redis
                redisTemplate.opsForValue().set(Vcode,event.getUser().getEmail(),30, TimeUnit.MINUTES );
                break;
            }else {
                log.info("redis========"+o.toString());
            }

        }
        User user = event.getUser();
        sendSimpleMailTool.sendMail("1837213978@qq.com", user.getEmail(), "用户注册", "注册码为:" +Vcode+"有效期为30分钟,请勿泄露给他人");

    }
}
